package edu.gyc.hiblog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import edu.gyc.hiblog.model.User;
import edu.gyc.hiblog.dao.UserDao;
import edu.gyc.hiblog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.gyc.hiblog.shiro.AccountProfile;
import edu.gyc.hiblog.util.Result;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2020-11-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Override
    public Result reg(User user) {
        int count = this.lambdaQuery().eq(User::getEmail, user.getEmail())
                .or().eq(User::getUsername, user.getUsername()).count();

        if (count > 0) {
            return Result.fail("用户名或邮箱已注册！");
        }

        user.setPassword(SecureUtil.md5(user.getPassword()));
        user.setCreated(new Date());
        user.setPoint(0);
        user.setVipLevel(0);
        user.setCommentCount(0);
        user.setPostCount(0);
        user.setAvatar("/res/images/avatar/default.png");
        this.save(user);
        return Result.success("恭喜你，注册成功！");
    }

    @Override
    public AccountProfile login(String email, String password) {
        User user=this.lambdaQuery().eq(User::getEmail,email).one();
        if (user == null) {
            throw new UnknownAccountException();
        }
        if (!user.getPassword().equalsIgnoreCase(password)) {
            throw new IncorrectCredentialsException();
        }

        user.setLasted(new Date());

        this.updateById(user);

        AccountProfile profile=new AccountProfile();
        BeanUtil.copyProperties(user, profile);

        return profile;
    }
}
